package com.kaifamiao.store.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaifamiao.store.system.domain.Menu;
import com.kaifamiao.store.system.mapper.MenuMapper;
import com.kaifamiao.store.system.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 10854
* @description 针对表【sys_menu】的数据库操作Service实现
* @createDate 2023-12-11 10:59:39
*/
@Service
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{

    @Override
    public List<Menu> selectMenusByRoleIds(Integer... roleIds) {
        return baseMapper.selectMenusByRoleIds(roleIds);
    }

    @Override
    public List<Tree<Integer>> buildTreeWithMenus(List<Menu> menus) {
        return getTrees(menus);
    }

    @Override
    public List<Tree<Integer>> selectMenuTreeByRoleIds(Integer... roleIds) {
        log.info("查询角色id为 {} 的菜单树", roleIds);
        List<Menu> menus = selectMenusByRoleIds(roleIds);

        return getTrees(menus);
    }

    private static List<Tree<Integer>> getTrees(List<Menu> menus) {
        // 构建树形菜单
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(2);

        List<Tree<Integer>> build = TreeUtil.build(menus, 0, treeNodeConfig, (treeNode, tree) -> {
            // tree 是返回的类型， treeNode传入的类型(menu)
            tree.setId(treeNode.getId());
            tree.setParentId(treeNode.getParentId());
            tree.setName(treeNode.getName());

            tree.putExtra("url", treeNode.getUrl());
            tree.putExtra("icon", treeNode.getIcon());
            tree.putExtra("sort", treeNode.getSort());
            tree.putExtra("type", treeNode.getType());
            tree.putExtra("createTime", treeNode.getCreateTime());
            tree.putExtra("updateTime", treeNode.getUpdateTime());
        });


        return build;
    }
}




